<?php
namespace app\admin\common\model;


use think\Model;

class Menu extends Model
{
    protected $pk = 'id';
    protected $table = 'qi_menu';

    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    protected $dateFormat = 'Y-m-d H:i:s';



    /*
     * 递归创建无极分类
     */
    public function getMenuRecursion($pid = 0)
    {
        $data = Menu::where('pid',$pid)->select()->toArray();

        $menuDatas = [];
        foreach ($data as $item) {
            $children['children'] = $this->getMenuRecursion($item['id']);
            $menuDatas[] = array_merge($item, $children);
        }
        return $menuDatas;
    }

    /*
     * 通过ID获取信息
     */
    public function getInfoById($id)
    {
        $data = Menu::where('id',$id)->find();
        return $data;
    }

    /*
     * 获取所有顶级菜单
     */
    public function getTopMenu()
    {
        $data = Menu::where('pid',0)->select();
        return $data;
    }

    /*
     * 添加菜单
     */
    public function addMenu($info)
    {
        $result = Menu::create($info);
        return $result;
    }

    /*
     * 更新菜单
     */
    public function editMenu($info)
    {
        $result = Menu::update($info);
        return $result;
    }

    /*
     * 删除菜单
     */
    public function delMenu($id)
    {
        $hasSon = Menu::where('pid',$id)->count();

        if ($hasSon) {
            exception('请先删除子菜单');
        }

        $result = Menu::where('id',$id)->delete();
        return $result;
    }
}